package v1

import (
	"copper-cloud/models"
	"copper-cloud/pkg/app"
	"copper-cloud/pkg/e"
	"copper-cloud/pkg/logging"
	"copper-cloud/pkg/util"
	"github.com/gin-gonic/gin"
	"net/http"
)

type User struct {
	Username string `form:"username"`
	Password string `form:"password"`
	DisplayName string `form:"display_name"`
	DeptId int `form:"dept_id"`
	RoleId int `form:"role_id"`
}

func AddUser(c *gin.Context) {

	traceId := util.GetTraceID(c)
	appG := app.Gin{C: c}

	var u User
	_ = c.ShouldBind(&u)
	logging.ZapLogger.Infow("添加用户", "用户", u)

	userIsExisted, _ := models.CheckAuth(u.Username, u.Password)
	if userIsExisted != nil {
		appG.Response(http.StatusBadRequest, e.InvalidParams, traceId, nil)
		return
	}

	dept, deptErr := models.GetDeptNameById(u.DeptId)
	if deptErr != nil {
		appG.Response(http.StatusBadRequest, e.InvalidParams, traceId, nil)
		return
	}

	role, roleErr := models.GetRoleNameById(u.RoleId)
	if roleErr != nil {
		appG.Response(http.StatusBadRequest, e.InvalidParams, traceId, nil)
		return
	}

	err := models.UserInsert(models.Users{
		Username:    u.Username,
		DisplayName: u.DisplayName,
		DeptId:      u.DeptId,
		DeptName:    dept.DeptName,
		RoleId:      u.RoleId,
		RoleName:    role.RoleName,
	})

	if err != nil {
		appG.Response(http.StatusInternalServerError, e.ERROR, traceId, nil)
		return
	}

	appG.Response(http.StatusOK, e.SUCCESS, traceId, nil)


}